package cmdb_account_management_v1

import (
	"context"

	cmdb_account_management_rpc "dfx_cmdb/cmdb-account-management-rpc/types/cmdb-account-management-rpc"
	"dfx_cmdb/cmdb-gateway/internal/svc"
	"dfx_cmdb/cmdb-gateway/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryAccountInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewQueryAccountInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryAccountInfoLogic {
	return &QueryAccountInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryAccountInfoLogic) QueryAccountInfo(req *types.QueryRequest) (resp *types.QueryAccountManagementResponse, err error) {
	// 转换 API 查询条件为 RPC 查询条件
	queryConditions := make([]*cmdb_account_management_rpc.QueryCondition, 0, len(req.QueryCondition))
	for _, cond := range req.QueryCondition {
		queryConditions = append(queryConditions, &cmdb_account_management_rpc.QueryCondition{
			Field: cond.Conditions,
			Op:    cond.QueryType,
			Value: cond.Values,
		})
	}

	grpcReq := &cmdb_account_management_rpc.QueryAccountInfoRequest{
		QueryCondition: queryConditions,
		Limit:          req.Limit,
		Page:           req.Page,
	}

	// 调用 RPC 服务
	grpcResp, err := l.svcCtx.CmdbAccountManagementRpc.QueryAccountInfo(l.ctx, grpcReq)
	if err != nil {
		logx.Errorf("调用 RPC 服务失败: %v", err)
		return nil, err
	}

	// 转换 RPC 响应为 API 响应
	accountList := make([]types.UpdateAccountInfoRequest, 0, len(grpcResp.UpdateAccessInfoRequest))
	for _, account := range grpcResp.UpdateAccessInfoRequest {
		accountList = append(accountList, types.UpdateAccountInfoRequest{
			Id:           account.Id,
			Type:         account.Type,
			Platform:     account.Platform,
			PlatformName: account.PlatformName,
			Account:      account.Account,
			Password:     account.Password,
			Token:        account.Token,
			Accesskey:    account.Accesskey,
			Accesssecret: account.Accesssecret,
			Comment:      account.Comment,
			OtherInfo:    account.OtherInfo,
		})
	}

	return &types.QueryAccountManagementResponse{
		AccountList: accountList,
		Total:       int64(len(accountList)),
	}, nil
}
